package com.qdxwx.web.controller.user;

import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.pdfUtils.VitaePdfUtils;
import com.qdxwx.common.upload.UploadUtils;
import com.qdxwx.common.utils.DateUtils;
import com.qdxwx.common.utils.FileUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.area.AreaService;
import com.qdxwx.data.service.user.UserVitaeService;
import com.qdxwx.data.service.user.UserWorkHistoryService;
import com.qdxwx.models.area.AreaFull;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserVitae;
import com.qdxwx.models.user.UserWorkHistory;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.Period;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user/vitae")
public class UserVitaeController extends BaseController {

    private static final String splitVline = "    |    ";

    @Autowired
    private UserVitaeService userVitaeService;
    @Autowired
    private UserWorkHistoryService userWorkHistoryService;
    @Autowired
    private AreaService areaService;

    @RequestMapping("/view.html")
    public String view(HttpServletRequest request, ModelMap mmap) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return VIEW_ERROR_403;
        }
        UserVitae userVitae = userVitaeService.getByUserId(user.getUserId());
        if (userVitae == null){
            return "redirect:/user/vitae/edit.html";
        }
        if(TKString.isNotEmpty(userVitae.getVitaePath())){
            //检查文件是否存在
            File file = new File(UploadConfig.uploadRoot + userVitae.getVitaePath());
            if (!file.exists()) {
                userVitae.setVitaePath(createVitaePdf(userVitae));
            }
        }else {
            userVitae.setVitaePath(createVitaePdf(userVitae));
        }
        mmap.put("userVitae",userVitae);
        mmap.put("user",user);
        return getViewPath("ucenter/uc-vitae-view");
    }

    @RequestMapping("/edit.html")
    public String info(HttpServletRequest request, ModelMap mmap) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return VIEW_ERROR_403;
        }
        UserVitae userVitae = userVitaeService.getByUserId(user.getUserId());
        List<UserWorkHistory> workHistorys = userWorkHistoryService.getListByUserId(user.getUserId());
        mmap.put("workHistorys", workHistorys);
        mmap.put("userVitae", userVitae != null ? userVitae : new UserVitae());
        mmap.put("provinces", areaService.getChildren(0));
        mmap.put("user", user);
        return getViewPath("ucenter/uc-vitae");
    }

    @PostMapping("/save.json")
    @ResponseBody
    public AjaxResult saveVitae(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.error("登录超时");
        }
        if(TKString.isEmpty(user.getAvatar())){
            return AjaxResult.error("请先完善个人信息头像上传");
        }
        UserVitae userVitae = userVitaeService.getByUserId(user.getUserId());
        if (userVitae != null) {
            if (userVitae.getUserId() != user.getUserId()) {
                return AjaxResult.error("请停止您的非法操作");
            }
        } else {
            userVitae = new UserVitae();
            userVitae.setUserId(user.getUserId());
        }

        String name = TKString.trim(request.getParameter("name"));
        if (TKString.isEmpty(name)) return AjaxResult.error("请输入名称");

        String nation = TKString.trim(request.getParameter("nation"));
        if (TKString.isEmpty(nation)) return AjaxResult.error("请输入您的民族");

        String nativePlace = TKString.trim(request.getParameter("nativePlace"));
        if (TKString.isEmpty(nativePlace)) return AjaxResult.error("请输入您的籍贯");

        String contactMobile = TKString.trim(request.getParameter("contactMobile"));
        if (!TKString.isMobile(contactMobile)) return AjaxResult.error("请输入您正确的手机号码");

        String contactEmail = TKString.trim(request.getParameter("contactEmail"));
        if (TKString.isNotEmpty(contactEmail)) {
            if (!TKString.isEmail(contactEmail)) {
                return AjaxResult.error("请输入您正确的邮箱地址");
            }
        }

        String education = TKString.trim(request.getParameter("education"));
        if (TKString.isEmpty(education)) return AjaxResult.error("请选择您的最高学历");

        String workExperience = TKString.trim(request.getParameter("workExperience"));
        if (TKString.isEmpty(workExperience)) return AjaxResult.error("请选择您的工作经验");

        String nowDwellAddres = TKString.trim(request.getParameter("nowDwellAddres"));
        if (TKString.isEmpty(nowDwellAddres)) return AjaxResult.error("请输入您现居住地址");

        String selfProfile = request.getParameter("selfProfile");
        if (TKString.isEmpty(selfProfile)) return AjaxResult.error("请输入自我简介");

        String jobPosition = TKString.trim(request.getParameter("jobPosition"));
        if (TKString.isEmpty(jobPosition)) return AjaxResult.error("请输入您期望的职位");

        int jobProvinceId = TKConvert.toInteger(request.getParameter("jobProvinceId"));
        if (jobProvinceId < 1) return AjaxResult.error("请选择您期望的工作省份");
        int jobCityId = TKConvert.toInteger(request.getParameter("jobCityId"));
        if (jobCityId > 0) {
            AreaFull areaFull = areaService.getAreaFull(jobCityId);
            if (areaFull != null) {
                userVitae.setJobCityId(areaFull.getCityId());
                userVitae.setJobCityName(areaFull.getName());
            }
        }

        String jobSkills = request.getParameter("jobSkills");
        if (TKString.isEmpty(jobSkills)) return AjaxResult.error("请输入您的职业技能或特长");

        String finishSchool = TKString.trim(request.getParameter("finishSchool"));
        if (TKString.isEmpty(finishSchool)) return AjaxResult.error("请输入您的毕业院校");

        userVitae.setName(name);
        userVitae.setAvatar(user.getAvatar());
        userVitae.setSex(TKConvert.toInteger(request.getParameter("sex"), 1));
        userVitae.setBirthday(TKConvert.toLocalDate(request.getParameter("birthday")));
        userVitae.setNation(nation);
        userVitae.setHeight(TKConvert.toInteger(request.getParameter("height")));
        userVitae.setNativePlace(nativePlace);
        userVitae.setContactMobile(contactMobile);
        userVitae.setContactEmail(contactEmail);
        userVitae.setEducation(education);
        userVitae.setWorkExperience(workExperience);
        userVitae.setNowDwellAddres(nowDwellAddres);
        userVitae.setSelfProfile(selfProfile);
        userVitae.setJobPosition(jobPosition);
        userVitae.setJobType(TKConvert.toInteger(request.getParameter("jobType"), 1));
        userVitae.setJobSalary(TKConvert.toInteger(request.getParameter("jobSalary")));
        userVitae.setJobProvinceId(jobProvinceId);
        userVitae.setJobSkills(jobSkills);
        userVitae.setFinishSchool(finishSchool);
        userVitae.setFinishDate(TKConvert.toLocalDate(request.getParameter("finishDate")));
        userVitae.setLearningType(TKConvert.toInteger(request.getParameter("learningType"), 1));
        userVitae.setMajor(TKString.trim(request.getParameter("major")));
        userVitae.setHonors(TKString.trim(request.getParameter("honors")));
        int row;
        if (userVitae.getId() > 0) {
            row = userVitaeService.updata(userVitae);
        } else {
            row = userVitaeService.insert(userVitae);
        }
        if(row > 0){
            //生成简历
            String vitaePath = createVitaePdf(userVitae);
            if(TKString.isNotEmpty(vitaePath)){
                FileUtils.deleteFile(UploadConfig.uploadRoot + userVitae.getVitaePath());
                userVitae.setVitaePath(vitaePath);
                userVitaeService.updateVitaePath(userVitae);
            }
        }
        return row > 0 ? AjaxResult.success(userVitae) : AjaxResult.error("系统异常，保存失败");
    }

    //简历下载
    @RequestMapping(value = {"/download.json"})
    @ResponseBody
    public AjaxResult Download(HttpServletRequest request) {
        User user = LoginUser.getUser(request);
        if (user == null) {
            return AjaxResult.auth("此功能需要登录才能下载");
        }
        UserVitae userVitae = userVitaeService.getByUserId(user.getUserId());
        if (userVitae == null) {
            return AjaxResult.error("请先保存更新简历再点击下载");
        }
        if(TKString.isNotEmpty(userVitae.getVitaePath())){
            //检查文件是否存在
            File file = new File(UploadConfig.uploadRoot + userVitae.getVitaePath());
            if (!file.exists()) {
                userVitae.setVitaePath(createVitaePdf(userVitae));
            }
        }else {
            userVitae.setVitaePath(createVitaePdf(userVitae));
        }
        return AjaxResult.success(userVitae.getVitaePath(), 1);
    }

    //生成简历地址
    public String createVitaePdf(UserVitae userVitae) {
        try {
            //创建文档
            Document document = new Document(PageSize.A4, 5, 5, 36, 36);
            //设置文档保存路径
            String vitaePath = UploadUtils.getSavePath(UploadConfig.uploadTempFolder, "pdf");
            File file = new File(UploadConfig.uploadRoot + vitaePath);
            if (!file.getParentFile().exists()) {
                if (!file.getParentFile().mkdirs()) {
                    System.out.println("创建目录失败：" + file.getPath());
                }
            }
            PdfWriter.getInstance(document, new FileOutputStream(UploadConfig.uploadRoot + vitaePath));
            document.open();
            Paragraph title = new Paragraph(18f, "个人简历", VitaePdfUtils.myfont(22, Font.BOLD));
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);
            document.add(VitaePdfUtils.blankRow(30));

            //基本信息
            PdfPTable tbBaseInfo = new PdfPTable(2);
            PdfPCell cell11 = new PdfPCell(new Paragraph(userVitae.getName(), VitaePdfUtils.myfont(18, Font.NORMAL)));
            cell11.setBorder(0);
            cell11.setPaddingBottom(10);
            cell11.setPaddingLeft(15);
            //头像
            String headImgPath = UploadConfig.uploadRoot + userVitae.getAvatar();
            Image headImg = Image.getInstance(headImgPath);
            //设置每列宽度比例
            int[] width11 = {15, 85};
            tbBaseInfo.setWidths(width11);
            tbBaseInfo.getDefaultCell().setBorder(0);
            PdfPCell cellHimg = new PdfPCell();
            cellHimg.setBorder(0);
            cellHimg.setImage(headImg);
            cellHimg.setColspan(1);//合并单元格
            cellHimg.setRowspan(3);
            tbBaseInfo.addCell(cellHimg);
            tbBaseInfo.addCell(cell11);
            StringBuilder cell12Str = new StringBuilder();
            cell12Str.append(userVitae.getSex() == 1 ? "男" : "女").append(splitVline);
            LocalDate start = userVitae.getBirthday();
            Period period = Period.between(start, LocalDate.now());
            int years = period.getYears();
            cell12Str.append(years).append(" 岁").append(splitVline);
            cell12Str.append(userVitae.getHeight()).append(" cm").append(splitVline);
            cell12Str.append(userVitae.getEducation()).append(splitVline);
            cell12Str.append(userVitae.getWorkExperience());
            PdfPCell cell12 = new PdfPCell(new Paragraph(cell12Str.toString(), VitaePdfUtils.myfont(12, Font.NORMAL)));
            cell12.setPaddingBottom(5);
            cell12.setPaddingLeft(15);
            cell12.setBorder(0);
            tbBaseInfo.addCell(cell12);
            PdfPCell cell13 = new PdfPCell(new Paragraph(userVitae.getContactMobile() + splitVline + userVitae.getContactEmail(), VitaePdfUtils.myfont(12, Font.NORMAL)));
            cell13.setBorder(0);
            cell13.setPaddingLeft(15);
            tbBaseInfo.addCell(cell13);
            document.add(tbBaseInfo);
            //加入空行
            document.add(VitaePdfUtils.blankRow(30));

            document.add(VitaePdfUtils.add_headtitle_1("求职意向"));
            //加入空行
            document.add(VitaePdfUtils.blankRow(5));
            //求职意向主体
            PdfPTable careerTable = new PdfPTable(4);
            //配置单元格跨页显示
            careerTable.setSplitLate(false);
            careerTable.setSplitRows(true);

            int[] careerTableWidth = {15, 35, 15, 35};
            careerTable.setWidths(careerTableWidth);
            careerTable.addCell(VitaePdfUtils.add_cell("期望职位：", "#878787", 10));
            careerTable.addCell(VitaePdfUtils.add_cell(userVitae.getJobPosition(), 10));
            careerTable.addCell(VitaePdfUtils.add_cell("意向省市：", "#878787", 10));
            StringBuilder jobCitystr = new StringBuilder();
            if (userVitae.getJobProvinceId() > 0) {
                AreaFull areaFull = areaService.getAreaFull(userVitae.getJobProvinceId());
                if (areaFull != null) {
                    jobCitystr.append(areaFull.getName());
                }
            }
            if (userVitae.getJobCityId() > 0) {
                jobCitystr.append(userVitae.getJobCityName());
            }
            careerTable.addCell(VitaePdfUtils.add_cell(jobCitystr.toString(), 10));
            careerTable.addCell(VitaePdfUtils.add_cell("期望薪资：", "#878787", 10));
            careerTable.addCell(VitaePdfUtils.add_cell(userVitae.getJobSalary(), 10));
            careerTable.addCell(VitaePdfUtils.add_cell("工作性质：", "#878787", 10));
            careerTable.addCell(VitaePdfUtils.add_cell(userVitae.getJobType() == 1 ? "全职" : "兼职", 10));
            document.add(careerTable);
            //加入空行
            document.add(VitaePdfUtils.blankRow());

            //专业技能
            document.add(VitaePdfUtils.add_headtitle_1("专业技能"));
            document.add(VitaePdfUtils.blankRow(5));
            VitaePdfUtils.add_ExplainExpTable(document, userVitae.getJobSkills());

            List<UserWorkHistory> workHistory = userWorkHistoryService.getListByUserId(userVitae.getUserId());
            if (workHistory.size() > 0) {
                document.add(VitaePdfUtils.blankRow());
                //工作经验
                document.add(VitaePdfUtils.add_headtitle_1("工作经验"));
                document.add(VitaePdfUtils.blankRow(5));
                for (UserWorkHistory history : workHistory) {
                    Map<String, String> map = new HashMap<>();
                    map.put("workUnit", history.getWorkUnit());
                    map.put("workDate", history.getWorkDate());
                    map.put("position", history.getPosition());
                    map.put("workIntro", history.getWorkIntro());
                    VitaePdfUtils.add_workExpTable(document, map);
                }
            }

            document.add(VitaePdfUtils.blankRow());

            //教育经历
            document.add(VitaePdfUtils.add_headtitle_1("教育经历"));
            document.add(VitaePdfUtils.blankRow(5));
            Map<String, String> educateMap = new HashMap<>();
            educateMap.put("finishSchool", userVitae.getFinishSchool());
            educateMap.put("major", userVitae.getMajor());
            educateMap.put("learningType", userVitae.getLearningType() == 1 ? "全日制" : "非全日制");
            educateMap.put("finishDate", DateUtils.toString(userVitae.getFinishDate(), "yyyy-MM"));
            VitaePdfUtils.add_eduExpTable(document, educateMap);

            document.add(VitaePdfUtils.blankRow());

            //在校荣誉
            document.add(VitaePdfUtils.add_headtitle_1("在校荣誉"));
            document.add(VitaePdfUtils.blankRow(5));
            VitaePdfUtils.add_ExplainExpTable(document, userVitae.getHonors());

            document.add(VitaePdfUtils.blankRow());

            //自我简介
            document.add(VitaePdfUtils.add_headtitle_1("自我简介"));
            document.add(VitaePdfUtils.blankRow(5));
            VitaePdfUtils.add_ExplainExpTable(document, userVitae.getSelfProfile());
            document.add(VitaePdfUtils.blankRow());
            document.close();
            userVitae.setVitaePath(vitaePath);
            userVitaeService.updateVitaePath(userVitae);
            return vitaePath;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }
}
